package com.flyco.modules.sync.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.flyco.common.api.vo.Result;
import com.flyco.modules.stm.entity.StmTask;
import com.flyco.modules.stm.entity.StmTaskHistory;
import com.flyco.modules.stm.mapper.StmTaskMapper;
import com.flyco.modules.stm.service.IStmTaskHistoryService;
import com.flyco.modules.stm.service.IStmTaskService;
import com.flyco.modules.util.SqlExecService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author hui_li
 * @Date 2021/3/9 17:29
 * @Version 1.0
 */
@Slf4j
@Api(tags="通知任务处理")
@RestController
@RequestMapping("/api/time/stm-task")
public class StmTaskController {
    @Autowired
    private IStmTaskService  stmTaskService;
    @Autowired
    private StmTaskMapper stmTaskMapper;
    @Autowired
    private IStmTaskHistoryService stmTaskHistoryService;
    @Autowired
    private Map<String,TaskProcess> processMap;
    @Autowired
    private SqlExecService sqlExecService;

    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {
        //转换日期 注意这里的转化要和传进来的字符串的格式一直 如2015-9-9 就应该为yyyy-MM-dd
        DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// CustomDateEditor为自定义日期编辑器
    }

    @ApiOperation(value="处理stmTask")
    @PostMapping(value = "/execTask/{taskType}")
    public Result<?> execTask(@PathVariable String taskType, @RequestBody Map<String, Object> params) {
        Date now = new Date();
        //处理的时间段，默认处理昨天的数据
        if(params.get("startTime")==null){
            params.put("startTime",DateUtil.beginOfDay(DateUtil.offsetDay(now,-1)));
        }
        if(params.get("endTime")==null){
            params.put("endTime",DateUtil.beginOfDay(now));
        }

        //查询任务
        LambdaQueryWrapper<StmTask> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(StmTask::getCancelFlag,0).le(StmTask::getStartTime,now).ge(StmTask::getEndTime,now).eq(StmTask::getType,taskType);
        List<StmTask> list = stmTaskService.list(queryWrapper);
        if(list.isEmpty()){
            return Result.ok("数据不存在！");
        }

        //执行任务
        AddCount addCount = new AddCount();
        TaskProcess taskProcess = processMap.get(taskType);
        if(taskProcess!=null){
            List<StmTask> orderTaskList = list.stream().filter(q -> StringUtils.isNotBlank(q.getTaskData()) && Objects.equals(q.getType(), taskType)).collect(Collectors.toList());
            addCount = taskProcess.exec(orderTaskList,now,params);
        }

        return Result.ok(DateUtil.formatDateTime(now)+" --> " + taskType + "执行完成！，共保存记录：" + addCount.count + "条\n");
    }

    interface TaskProcess{
        AddCount exec(List<StmTask> taskList, Date now, Map<String, Object> params);
    }

    @Service("order")
    class orderTaskProcess implements TaskProcess {
        @Override
        public AddCount exec(List<StmTask> orderTaskList, Date now, Map<String, Object> params) {
            log.info("orderTaskProcess#exec：orderTaskList={}",orderTaskList);
            AddCount addCount = new AddCount();
            orderTaskList.forEach(task -> {
                String sql = task.getTaskData();
                sqlExecService.select(sql, params, "store", sqlStr -> stmTaskMapper.executeSql(sqlStr)).forEach(oneMap -> {
                    StmTaskHistory stmTaskHistory = new StmTaskHistory();
                    stmTaskHistory.setTaskId(task.getId());
                    Map map = new HashMap();
                    map.put("orderId", oneMap.get("id"));
                    map.put("orderReceiveTime", oneMap.get("receive_time"));
                    map.put("userId", oneMap.get("user_id"));
                    map.put("userPhone", oneMap.get("receiver_phone"));
                    stmTaskHistory.setParam(JSONUtil.toJsonStr(map));
                    stmTaskHistory.setPartnerId(Integer.parseInt(oneMap.get("partner_id") + ""));
                    stmTaskHistory.setStoreId(Integer.parseInt(oneMap.get("store_id") + ""));
                    stmTaskHistory.setSalesId(Integer.parseInt(oneMap.get("sales_id") + ""));

                    String receiveTime = oneMap.get("receive_time") + "";
                    //订单创建时间+间隔天数，就是提醒的开始时间
                    DateTime startTime = DateUtil.offsetDay(DateUtil.parse(receiveTime), task.getIntervalDays());
                    stmTaskHistory.setStartTime(startTime);
                    //开始时间+开始后结束天数，就是提醒的截至时间
                    stmTaskHistory.setEndTime(DateUtil.offsetDay(startTime, task.getEndDays()));
                    stmTaskHistory.setStatus(0);
                    stmTaskHistory.setCreateTime(now);
                    stmTaskHistoryService.save(stmTaskHistory);
                    addCount.addCount();
                });
                //更新执行时间
                StmTask stmTask = new StmTask();
                stmTask.setId(task.getId());
                stmTask.setLastProcessTime(now);
                stmTaskService.updateById(stmTask);
            });
            return addCount;
        }
    }

    class AddCount{
        private Integer count = 0;
        public void addCount() {
            this.count++;
        }
    }

}
